package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service(interfaceClass = CheckGroupService.class)
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupMapper checkGroupMapper;
    @Override
    public void add(Integer[] checkItemIds, CheckGroup checkGroup) {
        //新增检查组
        checkGroupMapper.add(checkGroup);
        //新增检查组和检查项的中间表数据
        setCheckGroupAndCheckItem(checkItemIds,checkGroup.getId());


    }




    private void setCheckGroupAndCheckItem(Integer[] checkItemIds, Integer id) {
        if (checkItemIds!=null && checkItemIds.length>0){
            checkGroupMapper.setCheckGroupAndCheckItem(checkItemIds,id);
        }
    }


    /**
     * 分页检查组查询
     * @return
     */
    @Override
    public PageResult fandPage(QueryPageBean queryPageBean) {
        //定义当前页的页面和页码大小
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //条件查询所有数据
        List<CheckGroup> checkGroupList=checkGroupMapper.findByCondition(queryPageBean.getQueryString());
        //将查询的数据封装起来
        PageInfo<CheckGroup> pageInfo = new PageInfo<>(checkGroupList);
        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }

    @Override
    public void deleteById(Integer id) {
        //通过检查组id查询当前检查组是否二笔套餐引用
        Integer count =checkGroupMapper.findCountById(id);
        if (count>0){
            //如果被引用,则抛出异常,提示错误
            throw new RuntimeException(MessageConstant.CHECKITEM_IS_QUOTED);
        }
        //通过检查组的id检查检查组合检查项的中间表关系
        checkGroupMapper.deleteAssociation(id);
        //删除检查组
        checkGroupMapper.deleteById(id);

    }

    @Override
    public void edit(Integer[] checkItemIds, CheckGroup checkGroup) {
        //将检查组和检查项的中间表删除
        checkGroupMapper.deleteAssociation(checkGroup.getId());
        //重新添加检查组和检查项的中间表数据
        //新增中间表数据
        setCheckGroupAndCheckItem(checkItemIds,checkGroup.getId());
        //更新检查组数据
        checkGroupMapper.edit(checkGroup);
    }

    @Override
    public List<CheckGroup> findAll() {

        return checkGroupMapper.findAll();
    }
}
